﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace rusisControls.MVC.Helpers
{
    public static class EFHelper
    {
        public static IEnumerable<T> GetSortedData<T>(IQueryable<T> list, string sortColumnName, string sortDirection)
        {
            var type = typeof(T);
            var property = type.GetProperty(sortColumnName);
            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.Property(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);
            MethodCallExpression resultExp = (!string.IsNullOrEmpty(sortDirection) && sortDirection.ToLower() == "desc")
                ? Expression.Call(typeof(Queryable), "OrderByDescending", new[] { type, property.PropertyType }, list.Expression, Expression.Quote(orderByExp))
                : Expression.Call(typeof(Queryable), "OrderBy", new[] { type, property.PropertyType }, list.Expression, Expression.Quote(orderByExp));
            return (IEnumerable<T>)Expression.Lambda(resultExp).Compile().DynamicInvoke();
        }

        public static Func<T, object> GetField<T>(string field)
        {
            System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(field);
            //return obj => Convert.ToString(propertyInfo.GetValue(obj, null));
            //return obj => Convert.ToInt32(propertyInfo.GetValue(obj, null));
            return obj => propertyInfo.GetValue(obj, null);
        }

    }
}
